package groupb6.shopsystem.messaging.global;

import com.fasterxml.jackson.databind.ObjectMapper;
import groupb6.shopsystem.messaging.entity.Notice;
import groupb6.shopsystem.messaging.server.WebsocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/*
 * 全局WS对象，用于通知未加入连接的一方加入连接
 * @Author zhangyn
 * */
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/global/{userId}")
public class WSGlobalEndpoint {
    private static ObjectMapper jsonParser = new ObjectMapper();
    /**
     * 连接集合
     */
    private static final Map<Integer, Session> globalNoticeMap = WebsocketServer.getGlobalNoticeMap();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") Integer userId) {
        log.info("用户id：{} 加入了全局websocket连接。 ", userId);
        //将session添加到集合中
        globalNoticeMap.put(userId, session);
        //这段代码在缓冲中有东西时运行
        List<Integer> idList = WebsocketServer.getMessageCache().get(userId);//从缓存中取出
        if (idList != null && !idList.isEmpty()) {
            List<Notice> noticeList = new ArrayList<>();
            for (Integer id : idList) {
                Notice notice = new Notice();
                notice.setReceiverId(userId);
                notice.setSenderId(id);
                notice.setContent("在离线时收到了senderId=" + notice.getSenderId()+"的群组的新消息");
                noticeList.add(notice);
            }
            //在提醒后删除消息缓存
            WebsocketServer.getMessageCache().remove(userId);
            WebsocketServer.sendCachedNotices(noticeList, userId);//从缓存中发送
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam(value = "userId") Integer userId) {
        log.info("用户id：{} 退出了全局websocket连接。 ", userId);
        globalNoticeMap.remove(userId);
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable exception) {
        //TODO:处理连接错误时逻辑
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        //TODO:处理client发送消息的逻辑
    }

    public void pop(String message) {
    }


}
